package logic

import (
	"context"
	"fmt"
	"vipshop/model/mysql"
	"vipshop/model/redis"
	"vipshop/pkg"
	"vipshop/userrpc/internal/svc"
	"vipshop/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *userrpc.UserLoginRequest) (*userrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Client.Get("captchalogin" + in.Tel)
	if get.Val() != in.Captchacode {
		return nil, fmt.Errorf("图形验证码不正确，请重新输入")
	}

	cmd := redis.Client.Get("sendSmslogin" + in.Tel)
	if cmd.Val() != in.Sendsmscode {
		return nil, fmt.Errorf("短信验证码不正确，请重新输入")
	}
	var user mysql.User
	mysql.DB.Debug().Model(&mysql.User{}).Where("tel=?", in.Tel).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该手机号还没有注册，请重新输入")
	}
	if user.Password != pkg.PwdMD5(in.Password) {
		return nil, fmt.Errorf("密码不正确，请重新输入")
	}
	mysql.DB.Debug().Model(&mysql.User{}).Find(&user)
	redis.Client.Del("captchalogin" + in.Tel)
	redis.Client.Del("sendSmslogin" + in.Tel)

	return &userrpc.UserLoginResponse{Id: int64(user.ID)}, nil
}
